package mission_tour.solution;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsoluteLayout.LayoutParams;

public class tour_error_picture_search extends Activity implements ServerIp{
    /** Called when the activity is first created. */
	int sec = 60;
	private TimerTask second;
	TextView search_time_set;
	Handler handler = new Handler();
	AlertDialog.Builder nologin;
	Bitmap picture_img;
	ImageView check_picture;
	AbsoluteLayout picture_al;
	AbsoluteLayout.LayoutParams fparam;
	ImageView error_search_img;
	ImageView answer_title;
	
	URLConnection conn = null;
	InputStream is= null;
	URL imageURL;
	
	int check_x;
	int check_y;
	
	String[] get_picture_position_start_x;
    String[] get_picture_position_start_y;
    String[] get_picture_position_end_x;
    String[] get_picture_position_end_y;
    String[] get_explanation;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_error_picture_search);
        
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);	//	화면 안꺼짐
        
        items.picture_item_length = 0;
        
        error_search_img = (ImageView)findViewById(R.id.error_search_img);
        
        final ProgressDialog nowloding = ProgressDialog.show(tour_error_picture_search.this,"","틀린그림을 불러오고 있습니다....",true);
                
    	new Thread(new Runnable() {    
			@Override
			public void run() {
				try {
					imageURL = new URL(items.event_list.get(items.quiz_no).getPicture_link());	//이미지 링크 주소 불러옴
					conn = imageURL.openConnection();	//링크 접속 선언	
					conn.connect();						//링크 접속
					is = conn.getInputStream();
		 
					BufferedInputStream bis = new BufferedInputStream(is);		//접속 결과 버퍼에 담기
					picture_img = BitmapFactory.decodeStream(bis);				//비트맵 변수에 결과 담기
					bis.close();
					is.close();
					
					runOnUiThread(new Runnable(){
						 @Override
						 public void run() {
							 error_search_img.setImageBitmap(picture_img);			//이미지 그리기
						 }
					});
					nowloding.cancel();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
	    }).start();
    	
		second = new TimerTask() {
			public void run() {
				sec--;
				if(sec == -1 ){
					second.cancel();
					
					runOnUiThread(new Runnable(){
			            @Override
			             public void run() {
			            	Toast.makeText(tour_error_picture_search.this,"시간이 초과 되었습니다",Toast.LENGTH_SHORT).show();
			             }
			        });
					Intent intent = new Intent(tour_error_picture_search.this, quiz_failure.class);
					startActivityForResult(intent, 0);
					finish();
				}else{
					Update();
				}
			}
		};
		Timer timer = new Timer();
		timer.schedule(second, 0, 1000);
		
		picture_al = (AbsoluteLayout) findViewById(R.id.picture_al);
		
        if(items.event_list.get(items.quiz_no).getQuiz_answer() <= 2){
	        get_picture_position_start_x = items.event_list.get(items.quiz_no).getQuiz_picture_start_x().split("@");
			get_picture_position_start_y = items.event_list.get(items.quiz_no).getQuiz_picture_start_y().split("@");
			get_picture_position_end_x = items.event_list.get(items.quiz_no).getQuiz_picture_end_x().split("@");
			get_picture_position_end_y = items.event_list.get(items.quiz_no).getQuiz_picture_end_y().split("@");
			get_explanation = items.event_list.get(items.quiz_no).getQuiz_explanation().split("@");
        }
        
		error_search_img.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(items.event_list.get(items.quiz_no).getQuiz_answer() > 1){
					for(int i=0; i<get_picture_position_start_x.length; i++){
						if (((event.getX() >= Integer.parseInt(get_picture_position_start_x[i])) && (event.getX() <= Integer.parseInt(get_picture_position_end_x[i]))) && ((event.getY() >= Integer.parseInt(get_picture_position_start_y[i])) && (event.getY() <= Integer.parseInt(get_picture_position_end_y[i])))) {
							check_x = Integer.parseInt(get_picture_position_start_x[i]);
							check_y = Integer.parseInt(get_picture_position_start_y[i]);
							fparam = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, check_x,check_y);	//내 위치 표시되는 좌표 파람 (가로크기 , 세로크기 , X좌표 , Y좌표)
							
					        check_picture = new ImageView(tour_error_picture_search.this);	//체크 표시 이미지 생성
					        check_picture.setBackgroundResource(R.drawable.check);
							check_picture.setLayoutParams(fparam);							
							picture_al.addView(check_picture);								//체크 이미지 이미지 위에 붙이기
							
							String next_title = "더 찾기";
							items.picture_item_length++;
							if((items.picture_item_length == items.event_list.get(items.quiz_no).getQuiz_answer()) && (items.quiz_no+1) == items.event_list.size()){//퀴즈 모든문제 풀이 완료
								second.cancel();
								Handler pHandler = new Handler();
				            	pHandler.postDelayed(new Runnable() {
									@Override
									public void run() {
										// TODO Auto-generated method stub
										
										items.event_point_final += items.event_list.get(items.quiz_no).getQuiz_gift_point();
										Intent intent = new Intent(tour_error_picture_search.this, quiz_answer_ok.class);
										startActivityForResult(intent, 0);
										finish();										
									}

				            	}, 1000);
							}else{	//퀴즈 문제가 남았을 경우
								items.event_point_final += items.event_list.get(items.quiz_no).getQuiz_gift_point();
								if(items.picture_item_length == items.event_list.get(items.quiz_no).getQuiz_answer()){
									next_title = "다음문제로 이동";
									second.cancel();
								}								
						        AlertDialog.Builder search_ok = new AlertDialog.Builder(tour_error_picture_search.this)
						        .setTitle("정답입니다!")
						        .setMessage(get_explanation[i])
						        .setIcon(R.drawable.icon)
						        .setPositiveButton(next_title, new DialogInterface.OnClickListener(){
						        	@Override
									public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
						        		if(items.picture_item_length == items.event_list.get(items.quiz_no).getQuiz_answer()){
						        			items.quiz_no = items.quiz_no+1;
											if(items.event_list.get(items.quiz_no).getQuiz_type() == 3){
												Intent intent = new Intent(tour_error_picture_search.this, tour_error_picture_search.class);
												startActivityForResult(intent, 0);
												finish();
											}else if(items.event_list.get(items.quiz_no).getQuiz_type() == 1){
												Intent intent = new Intent(tour_error_picture_search.this, tour_oxquiz.class);
												startActivityForResult(intent, 0);
												finish();
											}
										}						        		
									}
								});
								search_ok.show();
							}
						}
					}
				}else{
					if (((event.getX() >= Integer.parseInt(items.event_list.get(items.quiz_no).getQuiz_picture_start_x())) && (event.getX() <= Integer.parseInt(items.event_list.get(items.quiz_no).getQuiz_picture_end_x()))) && ((event.getY() >= Integer.parseInt(items.event_list.get(items.quiz_no).getQuiz_picture_start_y())) && (event.getY() <= Integer.parseInt(items.event_list.get(items.quiz_no).getQuiz_picture_end_y())))) {
						second.cancel();
						check_x = Integer.parseInt(items.event_list.get(items.quiz_no).getQuiz_picture_start_x());
						check_y = Integer.parseInt(items.event_list.get(items.quiz_no).getQuiz_picture_start_y());
						fparam = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, check_x,check_y);	//내 위치 표시되는 좌표 파람 (가로크기 , 세로크기 , X좌표 , Y좌표)
				        check_picture = new ImageView(tour_error_picture_search.this);
				        check_picture.setBackgroundResource(R.drawable.check);
						check_picture.setLayoutParams(fparam);
						picture_al.addView(check_picture);
						if((items.quiz_no+1) == items.event_list.size()){//퀴즈 모든문제 풀이 완료
							Handler pHandler = new Handler();
			            	pHandler.postDelayed(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									items.event_point_final += items.event_list.get(items.quiz_no).getQuiz_gift_point();
									Intent intent = new Intent(tour_error_picture_search.this, quiz_answer_ok.class);
									startActivityForResult(intent, 0);
									finish();											
								}

			            	}, 1000);
						}else{	//퀴즈 문제가 남았을 경우
							Handler pHandler = new Handler();
			            	pHandler.postDelayed(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									items.event_point_final += items.event_list.get(items.quiz_no).getQuiz_gift_point();
							        AlertDialog.Builder search_ok = new AlertDialog.Builder(tour_error_picture_search.this)
							        .setTitle("정답입니다!")
							        .setMessage(items.event_list.get(items.quiz_no).getQuiz_explanation())
							        .setIcon(R.drawable.icon)
							        .setPositiveButton("다음문제로 이동", new DialogInterface.OnClickListener(){
							        	@Override
										public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
							        		items.quiz_no = items.quiz_no+1;
											if(items.event_list.get(items.quiz_no).getQuiz_type() == 3){
												Intent intent = new Intent(tour_error_picture_search.this, tour_error_picture_search.class);
												startActivityForResult(intent, 0);
												finish();
											}else if(items.event_list.get(items.quiz_no).getQuiz_type() == 1){
												Intent intent = new Intent(tour_error_picture_search.this, tour_oxquiz.class);
												startActivityForResult(intent, 0);
												finish();
											}
										}
									});
									search_ok.show();										
								}

			            	}, 1000);
						}
					}
				}				
				return false;
			}
		});
    }
    protected void Update() {
    	search_time_set = (TextView)findViewById(R.id.search_time_set);
    	
		Runnable updater = new Runnable() {
			public void run() {
				search_time_set.setText(sec+"");
			}
		};
		handler.post(updater);
	}
    
    public boolean onKeyDown( int KeyCode, KeyEvent event ){
		if( event.getAction() == KeyEvent.ACTION_DOWN ){
			if( KeyCode == KeyEvent.KEYCODE_BACK ){
				second.cancel();
				items.quiz_no = 0;
		        items.event_called = false;
				
				Intent intent = new Intent(tour_error_picture_search.this, tour_main.class);
				startActivityForResult(intent, 0);
				finish();
				
				return false;
			}
		}
		return super.onKeyDown(KeyCode, event);
	}
    public boolean onCreateOptionsMenu(Menu menu){
    	getMenuInflater().inflate(R.menu.quick, menu);
		return true;   	
    }

    public boolean onOptionsItemSelected(MenuItem item){
    	if(item.getItemId() == R.id.map_go){
    		startActivity(new Intent(this,tour_map.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.event_go){
    		startActivity(new Intent(this,tour_event_info.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.myinfo_go){
    		startActivity(new Intent(this,tour_myinfo.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.coupon_go){
    		startActivity(new Intent(this,tour_coupon.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.help_go){
    		startActivity(new Intent(this,tour_help.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.oxquiz_go){
    		items.event_list.removeAll(items.event_list);

    		new Thread(new Runnable() {    
				@Override
				public void run() {
					runOnUiThread(new Runnable(){
						 @Override
						 public void run() {
							 AlertDialog.Builder q_level = new AlertDialog.Builder(tour_error_picture_search.this)
				    			.setTitle(items.appname)
				    			.setMessage("퀴즈 난이도를 선택해 주세요")
				    			.setIcon(R.drawable.icon)
				    			.setPositiveButton("초급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_error_picture_search.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_easy);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_error_picture_search.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_error_picture_search.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			})
				    			.setNeutralButton("고급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_error_picture_search.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_hard);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_error_picture_search.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_error_picture_search.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			});
								q_level.show();
						 }
					 });
				}
		    }).start();
    	}
		return false;
    }
}
